package cn.feizhu.aimarket.ai.workflow.node;

import cn.feizhu.aimarket.ai.utils.JsonFixer;
import cn.feizhu.aimarket.ai.utils.JsonToObjectValidator;
import cn.feizhu.aimarket.ai.workflow.model.constant.WorkflowControlConstant;
import cn.feizhu.aimarket.ai.workflow.model.enums.NodeStatus;
import cn.feizhu.aimarket.model.dto.ai.outline.NovelOutlineResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;

import java.util.Map;
import java.util.Objects;

/**
 * 检查大纲生成节点是否是符合Json格式的
 *
 * @author feizhu
 * @since 2025/10/21
 */
public class OutlineCheckNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(OutlineCheckNode.class);

    private final Map<String, NodeStatus> node2Status;

    public static final String NODE_NAME = "outline_check";

    public OutlineCheckNode(ChatClient outLineChatClient, Map<String, NodeStatus> node2Status) {
        this.node2Status = node2Status;
    }

    @Override
    public Map<String, Object> apply(OverAllState state) {
        node2Status.put(NODE_NAME, NodeStatus.RUNNING);
        logger.info("=== 大纲检查节点开始执行 ===");

        try {
            // 原本的流式检测节点
            // 首先使用工具类进行检验是否可以转为JSON
            String rawOutline = (String) state.value(WorkflowControlConstant.OUTLINE).orElse("");
            // TODO 采用内置方法修复，直接调用就行 有多层机制包括简单括号匹配和智能字段映射
            NovelOutlineResponse outlineResponse = JsonFixer.smartJsonFixer(rawOutline, NovelOutlineResponse.class);
            // TODO 这里直接存储对象了 将大纲存储到状态中
            node2Status.put(NODE_NAME, NodeStatus.COMPLETED);
            return Map.of(WorkflowControlConstant.OUTLINE, outlineResponse);

        } catch (Exception e) {
            logger.error("大纲检查节点执行异常", e);
            node2Status.put(NODE_NAME, NodeStatus.FAILED);
            return Map.of(WorkflowControlConstant.OUTLINE, "大纲检查节点失败：" + e.getMessage());
        } finally {
            logger.info("=== 大纲检查节点执行完成 ===");
        }
    }
}
